<template>
  <transition name="search-overlay">
    <div v-if="isVisible" class="fixed inset-0 bg-black/80 z-51 flex items-center justify-center p-4" @click="handleOverlayClick">
      <!-- 搜索标题 -->
      <div class="absolute top-1/4 text-white text-3xl font-bold tracking-wide">
        文章搜索
      </div>
      
      <!-- 搜索输入框 -->
      <div class="w-full max-w-3xl" @click.stop>
        <div class="relative">
          <div class="absolute inset-y-0 left-0 flex items-center pl-6 pointer-events-none">
            <svg class="w-6 h-6 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m21 21-6-6m2-5a7 7 0 1 1-14 0 7 7 0 0 1 14 0Z"></path>
            </svg>
          </div>
          <input
            type="text" 
            class="block w-full py-6 pl-16 pr-6 text-xl bg-white/10 border border-white/20 rounded-full backdrop-blur-sm text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-white/30 transition-all"
            placeholder="输入文章关键词..."
            v-model="searchText"
            @input="performSearch"
            @keydown.enter="handleSearchSubmit"
            @keydown.esc="closeSearch"
            ref="searchInput"
          />
        </div>
        <!-- 搜索结果 -->
        <div v-if="searchResults.length > 0" class="mt-8 bg-white/5 backdrop-blur-sm rounded-xl p-6 max-h-96 overflow-y-auto">
          <div class="text-white mb-4 text-xl font-medium">搜索结果</div>
          <div class="space-y-4">
            <div 
              v-for="article in searchResults" 
              :key="article.id"
              @click="goToArticleDetail(article.id)"
              class="p-4 bg-white/5 hover:bg-white/10 rounded-lg transition-colors cursor-pointer"
            >
              <h3 class="text-white text-lg font-medium mb-2">{{ article.title }}</h3>
            </div>
          </div>
        </div>
        
        <!-- 无搜索结果提示 -->
        <div v-else-if="searchText.trim() && searchResults.length === 0" class="mt-8 bg-white/5 backdrop-blur-sm rounded-xl p-8 text-center">
          <p class="text-gray-300">未找到与 "{{ searchText }}" 相关的文章</p>
        </div>
      </div>
    </div>
  </transition>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { searchArticles } from '@/api/frontend/article'

// Props
const props = defineProps({
  isVisible: {
    type: Boolean,
    default: false
  }
})

// Emits
const emit = defineEmits(['close'])

// 响应式数据
const searchText = ref('')
const searchResults = ref([])
const searchInput = ref(null)
let searchTimeout = null
const router = useRouter()

// 监听isVisible变化，当显示时聚焦输入框
watch(() => props.isVisible, (newVal) => {
  if (newVal && searchInput.value) {
    setTimeout(() => {
      searchInput.value.focus()
    }, 100)
  }
})

// 执行搜索
const performSearch = () => {
  if (searchText.value.trim() === '') {
    searchResults.value = []
    return
  }

  // 防抖处理
  clearTimeout(searchTimeout)
  searchTimeout.value = setTimeout(() => {
    searchArticles(searchText.value)
      .then(response => {
        if (response.success) {
          searchResults.value = response.data || []
          console.log('搜索结果:', searchResults.value)
        }
      })
      .catch(error => {
        console.error('搜索文章失败:', error)
        searchResults.value = []
      })
  }, 300)
}

// 处理搜索提交
const handleSearchSubmit = () => {
  if (searchResults.value.length > 0) {
    goToArticleDetail(searchResults.value[0].id)
  }
}

// 跳转到文章详情页
const goToArticleDetail = (articleId) => {
  closeSearch()
  router.push({ path: '/article/detail', query: { articleId } })
}

// 关闭搜索遮罩层
const closeSearch = () => {
  searchText.value = ''
  searchResults.value = []
  emit('close')
}

// 处理遮罩层点击事件（点击空白部分关闭）
const handleOverlayClick = () => {
  closeSearch()
}

// 处理ESC键关闭
const handleEscKey = (event) => {
  if (event.key === 'Escape' && props.isVisible) {
    closeSearch()
  }
}

// 添加全局事件监听
onMounted(() => {
  document.addEventListener('keydown', handleEscKey)
})

// 移除全局事件监听
onUnmounted(() => {
  document.removeEventListener('keydown', handleEscKey)
  if (searchTimeout) {
    clearTimeout(searchTimeout)
  }
})
</script>

<style scoped>
/* 遮罩层过渡动画 */
.search-overlay-enter-active,
.search-overlay-leave-active {
  transition: opacity 0.3s ease;
}

.search-overlay-enter-from,
.search-overlay-leave-to {
  opacity: 0;
}

/* 搜索结果滚动条样式 */
::-webkit-scrollbar {
  width: 8px;
}

::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
}

::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.3);
  border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.5);
}

/* 移动端适配 */
@media (max-width: 768px) {
  .text-3xl {
    font-size: 2xl;
  }
  
  .text-xl {
    font-size: lg;
  }
  
  .py-6 {
    padding-top: 1rem;
    padding-bottom: 1rem;
  }
  
  .max-h-96 {
    max-height: 20rem;
  }
}
</style>